package com.lvyq.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lvyq.model.ai.TcGpt;
import com.lvyq.model.apiinfo.ApiInfo;
import com.lvyq.repository.api.ApiInfoRepository;
import lombok.extern.java.Log;
import org.junit.Test;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @program: weg
 * @description:Ai100 透传GPT
 * @author: lvyq
 * @create: 2023-04-21 08:59
 **/

@Log
public class TCGPTUtil {


    @Resource
    private ApiInfoRepository apiInfoRepository;

    public static String getAnswer(ApiInfo apiInfo,String question){
        String result = "";
        TcGpt tcGpt = new TcGpt();
        tcGpt.setStream(false);
        tcGpt.setPrompt("");
        tcGpt.setQuestion(question);
        String res = sendPost(apiInfo, JSONObject.toJSONString(tcGpt));
        JSONObject mav =JSONObject.parseObject(res);
        result=mav.getString("data");
        return result;
    }

    public static String sendPost(ApiInfo apiInfo, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(apiInfo.getUrl());
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("content-type","application/json");
            conn.setRequestProperty("Authorization","Bearer "+apiInfo.getToken());
            conn.setRequestProperty("Accept","application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            out.print(param);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(conn.getInputStream())); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var16) {
            System.out.println("发送 POST 请求出现异常！" + var16);
            var16.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return result;
    }





}
